<template>
  <c-form
    ref="formRef"
    label-width="80px"
    isDialog
    :model="formData"
    :rows="formRows"
    @submit="onSubmit"
  ></c-form>
</template>

<script setup name="material-confirm-popup" lang="jsx">
import { ref } from 'vue';

import { createMateralV2, editMateralTitle } from '@/apis/material';

import { ElMessage, ElMessageBox, ElInput } from 'element-plus';

// modal,pinia
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

// api

const emit = defineEmits(['refresh']);

const formData = ref({
  title: '',
  remark: '',
});

const formRows = ref([
  { formType: 'input', prop: 'title', label: '标题:' },
  {
    formType: 'input',
    prop: 'remark',
    type: 'textarea',
    placeholder: '请输入备注（可以为空）',
    label: '备注:',
    required: false,
  },
]);

const initData = () => {
  const modalData = modalStore.getModal();

  if (modalData) {
    formData.value.title = modalData.title;
    formData.value.remark = modalData.remark;
  }
};

initData();

const formRef = ref(null);
const onSubmit = async (values, instance, done) => {
  instance.loading = true;

  const modalData = modalStore.getModal();

  if (modalData._id) {
    let res = await editMateralTitle({ ...modalData, ...formData.value }).catch((err) => err);

    if (res.code == 0) {
      ElMessage.success('修改成功');
      done();
      modalStore.closeModal();
      emit('refresh');
    }
  } else {
    let res = await createMateralV2({ ...modalData, ...formData.value }).catch((err) => err);

    console.log(res, 'res');

    if (res.code == 0) {
      ElMessage.success('创建成功');
      done();

      modalStore.closeModal();
      setTimeout(() => {
        modalStore.openModal('material-copy-popup', { _id: res.data.id });
      }, 200);
    }
  }

  instance.loading = false;
};
</script>

<style lang="scss" scoped></style>
